Grokking Meta Coding Interview
Rate this course
Ask Author
Contribute
Back to course home

0% completed

Vote For New Content
Introduction
Who Should Take This Course?
Meta Easy Problems
Toeplitz Matrix (easy)
Solution: Toeplitz Matrix
Remove All Adjacent Duplicates In String (easy)
Solution: Remove All Adjacent Duplicates In String
Minimum Depth of a Binary Tree (easy)
Solution: Minimum Depth of a Binary Tree
Tree Diameter (easy)
Solution: Tree Diameter
Island Perimeter (easy)
Solution: Island Perimeter
Moving Average from Data Stream (easy)
Solution: Moving Average from Data Stream
Move Zeroes (easy)
Solution: Move Zeroes
Missing Ranges (easy)
Solution: Missing Ranges
Palindrome Permutation (easy)
Solution: Palindrome Permutation
Rank Transform of an Array (easy)
Solution: Rank Transform of an Array
Diagonal Traverse (medium)
Solution: Diagonal Traverse
Shortest Path in Binary Matrix (medium)
Solution: Shortest Path in Binary Matrix
Maximum Swap (medium)
Solution: Maximum Swap
Custom Sort String (medium)
Solution: Custom Sort String
Binary Tree Vertical Order Traversal (medium)
Solution: Binary Tree Vertical Order Traversal
Buildings With an Ocean View (medium)
Solution: Buildings With an Ocean View
Basic Calculator II (medium)
Solution: Basic Calculator II
Nested List Weight Sum (medium)
Solution: Nested List Weight Sum
Dot Product of Two Sparse Vectors (medium)
Solution: Dot Product of Two Sparse Vectors
Max Consecutive Ones III (medium)
Solution: Max Consecutive Ones III
Subarray Sum Equals K (medium)
Solution: Subarray Sum Equals K
Next Permutation (medium)
Solution: Next Permutation
Simplify Path (medium)
Solution: Simplify Path
Lowest Common Ancestor of a Binary Search Tree (medium)
Solution: Lowest Common Ancestor of a Binary Search Tree
'K' Closest Points to the Origin (medium)
Solution: 'K' Closest Points to the Origin
Sum of Path Numbers (medium)
Solution: Sum of Path Numbers
Merge Intervals (medium)
Solution: Merge Intervals
Right View of a Binary Tree (medium)
Solution: Right View of a Binary Tree
Number of Islands (medium)
Solution: Number of Islands
Clone Graph (medium)
Solution: Clone Graph
Missing Element in Sorted Array (medium)
Solution: Missing Element in Sorted Array
Number of Substrings Containing All Three Characters (medium)
Solution: Number of Substrings Containing All Three Characters
Capacity To Ship Packages Within D Days (medium)
Solution: Capacity To Ship Packages Within D Days
Count and Say (medium)
Solution: Count and Say
Contiguous Array (medium)
Solution: Contiguous Array
Sliding Window Median (hard)
Solution: Sliding Window Median
Alien Dictionary (hard)
Solution: Alien Dictionary
Minimum Window Substring (hard)
Solution: Minimum Window Substring
Best Meeting Point (hard)
Solution: Best Meeting Point
Maximum Sum of 3 Non-Overlapping Subarrays (hard)
Solution: Maximum Sum of 3 Non-Overlapping Subarrays
Making A Large Island (hard)
Solution: Making A Large Island
Basic Calculator (Hard)
Solution: Basic Calculator
Serialize and Deserialize Binary Tree (hard)
Solution: Serialize and Deserialize Binary Tree
Longest Increasing Path in a Matrix (hard)
Solution: Longest Increasing Path in a Matrix
Valid Palindrome III (hard)
Solution: Valid Palindrome III
Solution: Minimum Depth of a Binary Tree

Problem Statement

Given a root of the binary tree, find the minimum depth of a binary tree.

The minimum depth is the number of nodes along the shortest path from the root node to the nearest leaf node.

Examples

Example 1

Image

Example 2

Image

Constraints:

  • The number of nodes in the tree is in the range [0, 105].
  • -1000 <= Node.val <= 1000

Solution

To solve this problem, we use a Breadth-First Search (BFS) approach to find the minimum depth of a binary tree. BFS is ideal for this problem because it explores nodes level by level, ensuring that we find the closest leaf node (node without children) to the root as quickly as possible.

Starting from the root, we traverse the tree level by level, and for each node, we check if it is a leaf node. The moment we encounter the first leaf node, we return the depth of that node as it represents the minimum depth of the tree. By using a queue to keep track of nodes at each level, we can efficiently manage this traversal.

Step-by-Step Algorithm

  1. Check if the tree is empty:

    • If the root is null, return 0 as the tree has no depth.
  2. Initialize the BFS queue:

    • Create an empty queue and add the root node to it.
    • Initialize a variable minimumTreeDepth to 0 to keep track of the depth as we traverse each level.
  3. Start BFS traversal:

    • While the queue is not empty, perform the following steps:
      • Increment the minimumTreeDepth by 1 to account for the current level.
      • Determine the number of nodes at the current level by checking the size of the queue.
  4. Process each node at the current level:

    • For each node in the current level, perform the following:
      • Dequeue the node from the queue.
      • Check if the node is a leaf node (both left and right children are null).
      • If it is a leaf node, return the current minimumTreeDepth as this is the minimum depth of the tree.
  5. Add children to the queue:

    • If the node is not a leaf, add its left and right children to the queue (if they exist) to be processed in the next level.
  6. Repeat until the queue is empty:

    • Continue processing each level until the queue is empty, which indicates that all nodes have been traversed. The first leaf node encountered will provide the minimum depth.

Algorithm Walkthrough

Image
  1. Initialization:

    • Start with the root node 12.
    • Initialize an empty queue and add the root node 12 to it.
    • Set minimumTreeDepth to 0.
  2. Start BFS Traversal:

    • The queue contains [12].
    • Increment minimumTreeDepth to 1 because we are starting at the first level.
  3. Process the first level (root node 12):

    • The size of the queue is 1, indicating one node at this level.
    • Dequeue node 12 from the queue.
    • Check if node 12 is a leaf node (both left and right children are null):
      • Node 12 is not a leaf node, as it has left and right children.
    • Add the left child 7 and the right child 1 of node 12 to the queue.
    • The queue now contains [7, 1].
  4. Process the second level (nodes 7 and 1):

    • The queue contains [7, 1].

    • Increment minimumTreeDepth to 2 because we are moving to the second level.

    • The size of the queue is 2, indicating two nodes at this level.

    • Processing node 7:

      • Dequeue node 7 from the queue.
      • Check if node 7 is a leaf node:
        • Node 7 is a leaf node (no left or right children).
      • Since node 7 is a leaf node, return the current minimumTreeDepth, which is 2.

Final Output: The minimum depth of the tree [12, 7, 1, null, null, 10, 5] is 2.

Code

Here is the code for this algorithm:

Java
Saved to Cloud

. . . .

Complexity Analysis

Time Complexity

The time complexity of the above algorithm is , where ā€˜N’ is the total number of nodes in the tree. This is due to the fact that we traverse each node once.

Space Complexity

The space complexity of the above algorithm will be which is required for the queue. Since we can have a maximum of N/2 nodes at any level (this could happen only at the lowest level), therefore we will need space to store them in the queue.

Similar Problems

Problem 1: Given a binary tree, find its maximum depth (or height) using Tree BFS traversal.

Solution: We will follow a similar approach. Instead of returning as soon as we find a leaf node, we will keep traversing for all the levels, incrementing maximumDepth each time we complete a level. Here is what the code will look like:

Here is the visual representation of the algorithm:

Image

Code

Here is the code for this algorithm:

Java

. . . .

Complexity Analysis

Time Complexity

The time complexity of the above algorithm is , where ā€˜N’ is the total number of nodes in the tree. This is due to the fact that we traverse each node once.

Space Complexity

The space complexity of the above algorithm will be which is required for the queue. Since we can have a maximum of N/2 nodes at any level (this could happen only at the lowest level), therefore we will need space to store them in the queue.

Minimum Depth of a Binary Tree (easy)
Tree Diameter (easy)
Mark as Completed

On this page

Problem Statement

Examples

Solution

Step-by-Step Algorithm

Algorithm Walkthrough

Code

Complexity Analysis

Time Complexity

Space Complexity

Similar Problems

Code

Complexity Analysis

Time Complexity

Space Complexity